package com.todaynews;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.squareup.leakcanary.LeakCanary;
import com.todaynews.frame.logger.AndroidLogAdapter;
import com.todaynews.frame.logger.FormatStrategy;
import com.todaynews.frame.logger.Logger;
import com.todaynews.frame.logger.PrettyFormatStrategy;
import com.todaynews.frame.model.UserInfo;
import com.todaynews.utils.AndFixPatchManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * App application
 * @author jack
 */

public class AppDroid extends Application {

    private static AppDroid instance;
    private List<Activity> activities = new ArrayList<Activity>();
    private UserInfo userInfo;
    private static Looper mainLooper;//循环队列
    private static Handler handler;//主线程Handler
    private static Thread mainThread;//主线程
    private static long mainThreadId;//主线程id

    @Override
    public void onCreate() {
        super.onCreate();
        //全局Application
        instance = this;
        //对全局属性赋值
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid();
        handler = new Handler();
        Fresco.initialize(this);
        //图片压缩框架初始化
        //Tiny.getInstance().init(this);
        /**
         *日志打印初始化
         */
        //Initialize初始化
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(2)         // (Optional) How many method line to show. Default 2
                .methodOffset(3)        // (Optional) Skips some method invokes in stack trace. Default 5
//        .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag("Today")   // (Optional) Custom tag for each log. Default PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
        //todo
        Logger.d("message");
        Logger.w("no thread info and only 1 method");
        Logger.i("no thread info and method info");
        Logger.e("Custom tag for only one use");//错误信息 红色的
        Logger.json("{ \"key\": 3, \"value\": something}");
        Logger.d(Arrays.asList("foo", "bar"));
        Map<String, String> map = new HashMap<>();
        map.put("key", "value");
        map.put("key1", "value2");
        Logger.d(map);

        /**
         *LeakCanary 内存泄漏检测
         */
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);

        /**
         *
         * 初始化阿里AndFix
         */
        AndFixPatchManager.getInstance().initPatch(this);

    }

    public static AppDroid getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    /**
     * 新建了一个activity
     * @param activity
     */
    public void addActivity(Activity activity){
        if(activities!=null && !activities.contains(activity)){
            activities.add(activity);
        }
    }

    /**
     *  结束指定的Activity
     * @param activity-
     */
    public void finishActivity(Activity activity){
        if (activity!=null) {
            this.activities.remove(activity);
            activity.finish();
        }
    }

    /**
     *  结束指定的Activity
     */
    public void finishAllActivitys(){
        for(Activity a : activities) {
            if (a!=null) {
                a.finish();
            }
        }
    }

    /**
     * 应用退出，结束所有的activity
     */
    public void exitClient(){
        for(Activity activity : activities) {
            if (activity!=null) {
                activity.finish();
            }
        }
        System.exit(0);
    }

    /**
     * 重启当前应用
     */
    public static void restart() {
        Intent intent = getInstance().getPackageManager().getLaunchIntentForPackage(getInstance().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        getInstance().startActivity(intent);
    }

    public static Thread getMainThread() {
        return mainThread;
    }

    public static void setMainThread(Thread mMainThread) {
        AppDroid.mainThread = mMainThread;
    }

    public static long getMainThreadId() {
        return mainThreadId;
    }

    public static void setMainThreadId(long mMainThreadId) {
        AppDroid.mainThreadId = mMainThreadId;
    }

    public static Looper getMainThreadLooper() {
        return mainLooper;
    }

    public static void setMainThreadLooper(Looper mainLooper) {
        AppDroid.mainLooper = mainLooper;
    }

    public static Handler getMainHandler() {
        return handler;
    }

    public static void setMainHandler(Handler handler) {
        AppDroid.handler = handler;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

}